
package com.intercepter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.result.Result;
import com.vo.LoginData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class LoginAndPermissionInterceptor implements HandlerInterceptor {



    private static final  List<String> exceptUrls=Arrays.asList(
            "/login/backLogin",
            "/login/logout",
            "/login/getVerifyCode",
            "/login/resetPassword",
            "/uploadImg",
            "/uploadVideo",
            "/uploadApk",
            "/swagger-resources",
            "/systemMessage/**",
            "/getAlerMessageList**",
            "/getAlerMessageDetail",
            "/getAlerMessageList",
            "/getUnreadedMsgCount"
    );










	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
        String uri = request.getRequestURI();
        String reqFromHeader = request.getHeader("reqidentity");
        System.out.println("..........收到的请求:  "+request.getRequestURI()+" 得到的请求头是： "+reqFromHeader);
        if (exceptUrls.contains(uri)) return true;
        //取出header头，如果header标识的请求来源是管理后台，就进行登录拦截
        //检测是否登录
        if(ObjectUtils.isEmpty(reqFromHeader)){
           return true;
        } else{
            System.out.println("........收到来自backend的接口请求...."+reqFromHeader+"...ReqUrl : "+request.getRequestURI());
            LoginData data = (LoginData) request.getSession().getAttribute("curUser");
            if (data==null) {
                //重新登陆
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html; charset=utf-8");
                Result<Object> result = new Result<Object>().error(101, "请登录");
                response.getWriter().write(JSON.toJSONString(result, SerializerFeature.WriteMapNullValue));
                return false;
            }
        }
        return true;
	}

    @Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}


    public LoginAndPermissionInterceptor() {
    }
}
